import { getCookie, setCookie, expireCookie } from 'redux-cookie';
import Logger from './logger';
import _ from './lodash';
// 类型定义
import { Storage, OnComplete } from 'redux-persist';

// logger
const logger = Logger.get('utils_persist');
const STATE_KEY = 'persist-state';


/**
 * 使用cookie实现PersistStorage
 */
export class CookieStorage implements Storage {
  dispatch: Function;
  /**
   * 构造函数
   */
  constructor(dispatch: Function) {
    this.dispatch = dispatch;
  }

  setItem(key: string, value: any, onComplete?: OnComplete<any>): Promise<any> {
    logger.info('setItem');
    return new Promise((resolve, reject) => {
      let json = {};
      // 查询cookies
      const stateStr = this.dispatch(getCookie(STATE_KEY));
      if (stateStr) {
        // 反序列化成json对象
        json = JSON.parse(decodeURIComponent(stateStr));
      }
      json = _.set(key, value)(json);
      // 重新保存到cookie
      this.dispatch(setCookie(STATE_KEY, JSON.stringify(json)));
      onComplete && onComplete();
      resolve();
    });
  }

  getItem(key: string, onComplete?: OnComplete<any>): Promise<any> {
    logger.info('getItem');
    return new Promise((resolve, reject) => {
      // 查询cookies
      const stateStr = this.dispatch(getCookie(STATE_KEY));
      let result = undefined;
      if (stateStr) {
        // 反序列化成json对象
        const json = JSON.parse(decodeURIComponent(stateStr));
        logger.info(json);
        // 求得对象的key
        result = _.get(key)(json);
        logger.info(result);
      }
      onComplete && onComplete(null, result);
      resolve(result);
    });
  }

  removeItem(key: string, onComplete?: OnComplete<any>): Promise<any> {
    logger.info('removeItem');
    return new Promise((resolve, reject) => {
      let json = {};
      // 查询cookies
      const stateStr = this.dispatch(getCookie(STATE_KEY));
      if (stateStr) {
        // 反序列化成json对象
        json = JSON.parse(decodeURIComponent(stateStr));
      }
      json = _.set(key, undefined)(json);
      // 重新保存到cookie
      this.dispatch(setCookie(STATE_KEY, JSON.stringify(json)));
      onComplete && onComplete();
      resolve();
    });
  }

  getAllKeys(onComplete?: OnComplete<string[]>): Promise<string[]> {
    logger.info('getAllKeys');
    return new Promise((resolve, reject) => {
      // 查询cookies
      const stateStr = this.dispatch(getCookie(STATE_KEY));
      logger.debug(stateStr);
      logger.debug(decodeURIComponent(stateStr));
      let keys: string[] = [];
      if (stateStr) {
        // 反序列化成json对象
        const json = JSON.parse(decodeURIComponent(stateStr));
        // 求得对象的key
        logger.debug(json);
        keys = _.keys(json);
      }
      logger.debug(keys);
      onComplete && onComplete(null, keys);
      resolve(keys);
    });
  }
}

// export const cookieStorage = new CookieStorage();
